package com.iqilu.ksd.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.MySubsAdapter;
import com.iqilu.ksd.adapter.PaikeAdapter;
import com.iqilu.ksd.bean.PaikeBean;
import com.iqilu.ksd.bean.SubsItemBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.RequestBody;

/**
 * 我订阅的栏目
 * Created by Coofee on 2017/4/16.
 */

public class MySubsActivity extends BaseActivity {

    private static final String TAG = "MySubsActivity";

    private int page;
    private ArrayList<SubsItemBean> list;
    private MySubsAdapter adapter;

    private ImageView btLeft;
    private TextView tvTitle;
    private ImageView imgEmpty;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private RelativeLayout layLoading;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common_list);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();

        adapter = new MySubsAdapter(this,true);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        adapter.setOnItemClickListener(new MySubsAdapter.OnItemClickListener() {
            @Override
            public void OnItemClickListener(View view, int position) {
                int catid = list.get(position).getCatid();
                Intent intent = new Intent(MySubsActivity.this,SubsDetailActivity.class);
                intent.putExtra("catid",catid);
                startActivity(intent);
            }
        });
        adapter.setOnSubscribleListener(new MySubsAdapter.OnSubscribleListener() {
            @Override
            public void OnSubscribleListener(View view, int position) {
                if(list.get(position).getSubscribed() == 1){
                    delSubscribe(position);
                }else {
                    addSubscribe(position);
                }
            }
        });
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(false);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });
        rvList.setAdapter(adapter);
        page = 1;
        getList();

    }

    private void initView() {
        btLeft = getView(R.id.bt_left);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        imgEmpty = getView(R.id.img_empty);
        xRefreshView = getView(R.id.xRefreshView);
        rvList = getView(R.id.rv_list);
        layLoading = getView(R.id.lay_loading);

        tvTitle.setText(getString(R.string.me_subs));
        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(Activity.RESULT_OK);
                finish();
            }
        });
        layLoading.setVisibility(View.VISIBLE);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
    }

    private void getList() {
        String url = Api.URL_SUBSCRIBE + "?page=" + page;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                xRefreshView.stopRefresh();
                layLoading.setVisibility(View.GONE);
                if(page == 1){
                    xRefreshView.setVisibility(View.GONE);
                    imgEmpty.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onResponse(String response, int id) {
                xRefreshView.stopRefresh();
                layLoading.setVisibility(View.GONE);
                ArrayList<SubsItemBean> result = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<SubsItemBean>>() {
                });
                if (page == 1) {
                    if (result == null || result.size() == 0) {
                        imgEmpty.setVisibility(View.VISIBLE);
                        xRefreshView.setVisibility(View.GONE);
                        Toast.makeText(MySubsActivity.this, R.string.list_empty, Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        list = result;
                        adapter.setData(list);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    xRefreshView.stopLoadMore();
                    if (result == null || result.size() == 0) {
                        Toast.makeText(MySubsActivity.this, R.string.list_not_have, Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        list.addAll(result);
                        adapter.setData(list);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    private void addSubscribe(final int position) {
        int catid = list.get(position).getCatid();
        String catname = list.get(position).getCatname();
        String type = list.get(position).getType();
        String url = Api.URL_SUBSCRIBE + "?catid=" + catid + "&catname=" + catname + "&type=" + type;
        OkHttpUtils
                .put()
                .url(url)
                .requestBody(RequestBody.create(null, "something"))
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(MySubsActivity.this, R.string.my_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        status = JSONUtils.filterInt(response,"status",0);
                        if (status == 1) {
                            list.get(position).setSubscribed(1);
                            adapter.notifyDataSetChanged();
                            Toast.makeText(MySubsActivity.this, R.string.my_add_success, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MySubsActivity.this, R.string.my_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void delSubscribe(final int position) {
        int catid = list.get(position).getCatid();
        String type = list.get(position).getType();
        String url = Api.URL_SUBSCRIBE + "?catid=" + catid + "&type=" + type;
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(MySubsActivity.this, R.string.my_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                int status = 0;
                status = JSONUtils.filterInt(response,"status",0);
                if (status == 1) {
                    list.get(position).setSubscribed(0);
                    adapter.notifyDataSetChanged();
                    Toast.makeText(MySubsActivity.this, R.string.my_del_success, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MySubsActivity.this, R.string.my_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void finish() {
        setResult(Activity.RESULT_OK);
        super.finish();
    }
}
